package com.example.hello.service.impl;

import com.aliyun.oss.OSS;
import com.example.hello.entity.EmpAvatarDO;
import com.example.hello.mapper.EmpAvatarMapper;
import com.example.hello.model.AvatarUploadResponse;
import com.example.hello.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList(
            "image/png", "image/jpeg", "image/jpg");
    private static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB

    @Autowired
    private OSS ossClient;

    @Autowired
    private EmpAvatarMapper empAvatarMapper;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Override
    @Transactional
    public AvatarUploadResponse uploadAvatar(MultipartFile file, Integer empId) {
        // 验证文件类型
        if (!ALLOWED_CONTENT_TYPES.contains(file.getContentType())) {
            throw new RuntimeException("仅支持PNG/JPEG/JPG格式（检测到：" + file.getContentType() + "）");
        }

        // 验证文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new RuntimeException("文件大小不能超过2MB");
        }

        try {
            // 读取图片尺寸
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                throw new RuntimeException("无效的图片文件");
            }

            // 生成文件名
            String fileName = String.format("EMP%d_%d.%s",
                    empId,
                    Instant.now().getEpochSecond(),
                    getFileExtension(file.getOriginalFilename()));

            // 存储路径
            String storagePath = "图片/" + fileName;

            // 上传到OSS
            ossClient.putObject(bucketName, storagePath, new ByteArrayInputStream(file.getBytes()));

            // 保存到数据库
            EmpAvatarDO avatar = EmpAvatarDO.builder()
                    .empId(empId)
                    .imageName(fileName)
                    .build();

            // 查询是否已存在头像记录
            EmpAvatarDO existingAvatar = empAvatarMapper.selectByEmpId(empId);
            if (existingAvatar != null) {
                // 更新记录
                empAvatarMapper.updateByEmpId(avatar);
            } else {
                // 插入新记录
                empAvatarMapper.insert(avatar);
            }

            // 构建返回结果
            return AvatarUploadResponse.builder()
                    .code("AVATAR_UPLOAD_SUCCESS")
                    .storagePath("/" + storagePath)
                    .cdnUrl("https://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + storagePath)
                    .dimensions(AvatarUploadResponse.Dimensions.builder()
                            .width(image.getWidth())
                            .height(image.getHeight())
                            .build())
                    .build();

        } catch (IOException e) {
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }

    private String getFileExtension(String fileName) {
        if (fileName == null)
            return "jpg";
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex == -1 ? "jpg" : fileName.substring(lastDotIndex + 1).toLowerCase();
    }
}